package main.java.com.lee.juc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description TODO
 * @Author winston
 * @DateTime 2022/2/11
 */
public class DeadLockDemo {

    public static void main(String[] args) throws InterruptedException {
        ReentrantLock lock1 = new ReentrantLock();
        ReentrantLock lock2 = new ReentrantLock();

        Thread t1 = new Thread("t1") {
            @Override
            public void run() {
                lockDemo(lock1, lock2);
            }
        };

        Thread t2 = new Thread("t2") {
            @Override
            public void run() {
                lockDemo(lock2, lock1);
            }
        };

        t1.start();
        t2.start();
        t1.join();
        t2.join();
    }

    private static void lockDemo(Lock lock1, Lock lock2) {
        lock1.lock();
        System.out.println("线程: " + Thread.currentThread().getName() + "加锁: " + lock1.toString() + "成功");
        lock2.lock();
        System.out.println("线程: " + Thread.currentThread().getName() + "加锁: " + lock2.toString() + "成功");
        lock2.unlock();
        lock1.unlock();
    }
}
